package com.tp.utils;

import java.util.Random;

public class RandomUtils {
	
	/**
	 * 随机密码
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomPwd(int length) {
		StringBuilder pwd = new StringBuilder();
		String number = "0123456789";
		while (pwd.length() < length) {
			pwd.append(number.charAt((int) (Math.random() * number.length())));
		}
		return pwd.toString();
	}

	// 随机字符串
	private static final String _INT = "0123456789";
	private static final String _STR_U = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private static final String _STR_L = "abcdefghijklmnopqrstuvwxyz";
	private static final String _INT_STR_L = _INT + _STR_L;
	private static final String _STR = _STR_U + _STR_L;
	private static final String _ALL = _INT + _STR_U + _STR_L;

	private static final Random RANDOM = new Random();

	/**
	 * 生成的随机数类型
	 */
	public static enum RandomType {
		INT, STRING, LOWER, UPPER, ISTR, ALL;
	}

	/**
	 * 随机数生成
	 * 
	 * @param count
	 * @return
	 */
	public static String random(int count, RandomType randomType) {
		if (count == 0)
			return "";
		if (count < 0) {
			throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
		}
		char[] buffer = new char[count];
		for (int i = 0; i < count; i++) {
			if (randomType.equals(RandomType.INT)) {
				buffer[i] = _INT.charAt(RANDOM.nextInt(_INT.length()));
			} else if (randomType.equals(RandomType.STRING)) {
				buffer[i] = _STR.charAt(RANDOM.nextInt(_STR.length()));
			} else if (randomType.equals(RandomType.UPPER)) {
				buffer[i] = _STR.charAt(RANDOM.nextInt(_STR_U.length()));
			} else if (randomType.equals(RandomType.LOWER)) {
				buffer[i] = _STR.charAt(RANDOM.nextInt(_STR_L.length()));
			} else if (randomType.equals(RandomType.ISTR)) {
				buffer[i] = _INT_STR_L.charAt(RANDOM.nextInt(_INT_STR_L.length()));
			} else {
				buffer[i] = _ALL.charAt(RANDOM.nextInt(_ALL.length()));
			}
		}
		return new String(buffer);
	}
}
